﻿using System;
using System.Windows.Markup;
using System.Windows.Input;
using System.Windows.Data;

namespace PlanetWPF.Toolbelt.Utils
{
    /// <summary>
    /// Provides a Markup Extension for Registering an EventHandler for the
    /// <see cref="CommandBinding.Executed"/> event.
    /// </summary>
    public class ExecutedHandlerExtension:MarkupExtension
    {
        /// <summary>
        /// The Target object that implements the handler.
        /// </summary>
        public Object Target { get; set; }

        /// <summary>
        /// The name of the function on the object that handles the event.
        /// </summary>
        public String Handler { get; set; }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            ExecutedRoutedEventHandler retval=null;
            if (Target == null)
            {
                throw new Exception("Target cannot be Null.");
            }
            if(Target is ObjectDataProvider)
            {
                Target = ((ObjectDataProvider) Target).Data;
            }
            var type = Target.GetType();
            var function =
                type.GetMethod(
                    Handler,
                    new[]
                        {
                            typeof (Object),
                            typeof (ExecutedRoutedEventArgs)
                        });
            if (function != null)
            {
                retval = ((obj, args) => function.Invoke(Target, new[] {obj, args}));
            }
            return retval;
        }
    }
}